package DataAccessObject.entity; 

import java.text.ParsePosition;
import java.text.SimpleDateFormat;

import DataAccessObject.DAO;
import entity.Alumno;
import entity.Asignatura;
import entity.Matricula;

public class MatriculaDAO extends DAO<Matricula.Pk, Matricula> {
  
  public MatriculaDAO() throws Exception {
    super();
  }// Constructor
  
  public Matricula insert(int dni, int cod, String curso) throws Exception {
    Alumno alu = new AlumnoDAO().findById(dni);
    if (alu == null) {
      System.out.println("Falta insertar el alumno");
      return null;
    }// if

    Asignatura asig = new AsignaturaDAO().findById(cod);
    if (asig == null) {
      System.out.println("Falta insertar la asignatura");
      return null;
    }// if

    Matricula entity = findById(dni, cod, curso);
    if (entity != null) {
      System.out.println("Valor insertado");
      return null;
    }// if
    entity = new Matricula(cod, new SimpleDateFormat("yyyy").parse(curso, new ParsePosition(5)), dni);
    try {
      this.persist(entity);
    } catch (Exception e) {
      e.printStackTrace();
      entity = null;
    }// try-catch
    return entity;
  }// insert

  public Matricula delete(int dni, int cod, String curso) {
    Matricula entity = null;
    Matricula.Pk id = new Matricula.Pk();
    id.setDni(dni);
    id.setCod(cod);
    id.setCurso(new SimpleDateFormat("yyyy").parse(curso, new ParsePosition(5)));
    try {
      entity = this.remove(id);
    } catch (Exception e) {
      e.printStackTrace();
      entity= null;
    }// try-catch
    return entity;
  }// delete

  public Matricula findById(int dni, int cod, String curso) {
    Matricula.Pk id = new Matricula.Pk();
    id.setDni(dni);
    id.setCod(cod);
    id.setCurso(new SimpleDateFormat("yyyy").parse(curso, new ParsePosition(5)));
    return this.findById(id);
  }// findById

}// class MatriculaDAO